//
//  PKDatiView.m
//  Learn
//
//  Created by apple on 2024/4/7.
//  Copyright © 2024 迟建国. All rights reserved.
//

#import "PKDatiView.h"
#import "PkMatchModel.h"
@interface pkDatiCell :UITableViewCell
/* <#描述#> */
@property (nonatomic, strong) UIView    * bgView;
@property (nonatomic, strong) UILabel    * titleLabel;
@property (nonatomic, strong) UIImageView    * stateIconMy;
@property (nonatomic, strong) UIImageView    * stateIconOther;
@end

@implementation pkDatiCell

- (instancetype)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier {
    self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
    if (self) {
        self.backgroundColor = UIColor.clearColor;
        self.contentView.backgroundColor = UIColor.clearColor;
        
        self.selectionStyle = UITableViewCellSelectionStyleNone;
        [self createUI];
    }
    return self;
}
- (void)createUI {
    [self.contentView addSubview:self.bgView];
    [self.bgView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(self.contentView).insets(UIEdgeInsetsMake(5, 15, 5, 15));
//        make.left.equalTo(self.contentView).insets(15);
//        make.right.equalTo(self.contentView).offset(-15);
//        make.top.equalTo(self.contentView).offset(5);
//        make.bottom.equalTo(self.contentView).offset(-5);

    }];
    [self.bgView addSubview:self.titleLabel];
    [self.bgView addSubview:self.stateIconMy];
    [self.bgView addSubview:self.stateIconOther];
    
   
    [self.stateIconOther mas_makeConstraints:^(MASConstraintMaker *make) {
        make.width.height.offset(18);
        make.centerY.equalTo(self.bgView);
        make.right.equalTo(self.bgView).offset(-30);
    }];
    [self.stateIconMy mas_makeConstraints:^(MASConstraintMaker *make) {
        make.width.height.offset(18);
        make.centerY.equalTo(self.bgView);
        make.left.equalTo(self.bgView).offset(30);
    }];
    [self.titleLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.bottom.equalTo(self.bgView);
        make.left.equalTo(self.stateIconMy.mas_right).offset(5);
        make.right.equalTo(self.stateIconOther.mas_left).offset(-5);
    }];
}
- (UIImageView *)stateIconMy {
    if(!_stateIconMy){
        _stateIconMy = [[UIImageView alloc]init];
        _stateIconMy.contentMode = UIViewContentModeScaleAspectFill;
        _stateIconMy.image = [UIImage imageNamed:@"rightIcon"];//wrongIcon
        _stateIconMy.hidden = YES;
    }
    return _stateIconMy;
}
- (UIImageView *)stateIconOther {
    if(!_stateIconOther){
        _stateIconOther = [[UIImageView alloc]init];
        _stateIconOther.contentMode = UIViewContentModeScaleAspectFill;
        _stateIconOther.image = [UIImage imageNamed:@"rightIcon"];//wrongIcon
        _stateIconOther.hidden = YES;
    }
    return _stateIconOther;
}
- (UILabel *)titleLabel {
    if(!_titleLabel){
        _titleLabel = [[UILabel alloc]init];
        _titleLabel.text = @"";
        _titleLabel.numberOfLines = 0;
        _titleLabel.textColor = [UIColor blackColor];
        _titleLabel.font = PingFangMediumFont(16);
        _titleLabel.textAlignment = NSTextAlignmentCenter;
    }
    return _titleLabel;
}
- (UIView *)bgView {
    if(!_bgView){
        _bgView = [[UIView alloc]init];
        _bgView.backgroundColor = [UIColor whiteColor];
        _bgView.layer.cornerRadius = 22;
        _bgView.layer.masksToBounds = YES;
    }
    return _bgView;
}


- (void)updateItemCellModel:(id)itemModel {
    if ([itemModel isKindOfClass:PkWordModel.class]) {
        PkWordModel *model = (PkWordModel *)itemModel;
        self.titleLabel.text = model.pretations;
        self.stateIconMy.hidden = YES;
        self.stateIconOther.hidden = YES;
        self.stateIconOther.image = self.stateIconMy.image = model.isRight ? [UIImage imageNamed:@"rightIcon"]:[UIImage imageNamed:@"wrongIcon"];
        self.titleLabel.textColor = model.isRight?rgba(12, 183, 108, 1):rgba(244, 85, 85, 1);
        if (model.selected) {
            
            self.bgView.alpha = 0.3;
            self.stateIconMy.hidden = !model.mySelected;
            self.stateIconOther.hidden = !model.otherSelected;
            if (model.mySelected) {
                self.bgView.alpha = 1;
            }
            if (model.otherSelected) {
                self.bgView.alpha = 1;
            }
            
            if (model.isRight) {
                self.bgView.alpha = 1;
            }
            
        }else{
           
            self.bgView.alpha = 1;
            self.titleLabel.textColor = rgba(51, 51, 51, 1);
            
        }
       
    }
}

@end
@interface PKDatiView()<UITableViewDelegate,UITableViewDataSource>

@property (nonatomic, strong) UIView    * pkView;

@property (nonatomic, strong) UILabel    * pkLabel;

@property (nonatomic, strong) UIImageView    * leftUserImg;
@property (nonatomic, strong) UILabel    * leftUserName;
@property (nonatomic, strong) UIImageView    * rightUserImg;
@property (nonatomic, strong) UILabel    * rightUserName;


@property (nonatomic, strong) UIView    * proBgView;
@property (nonatomic, strong) UIView    * proView;
@property (nonatomic, strong) UILabel    * ringLabel;

@property (nonatomic, strong) UILabel    * wordLabel;

@property (nonatomic, strong) UITableView    * mTableView;
@property (nonatomic, strong) NSMutableArray    * dataArray;
@property (nonatomic, strong) PkWordModel    * rightWord;
@property (nonatomic, strong) PkMatchModel    * matchModel;
@property (nonatomic, assign) NSInteger            index;       //
@property (nonatomic, assign) BOOL            muteSelect;       //
@property (nonatomic, assign) NSInteger            timeNum;       //

@property (nonatomic, assign) NSInteger            myPkTime;       //
@property (nonatomic, assign) NSInteger            otherPkTime;       //
@property (nonatomic, strong) dispatch_source_t    timer;

@property (nonatomic, strong) NSMutableArray    * myResultArray;
@property (nonatomic, strong) NSMutableArray    * otherResultArray;


@end

@implementation PKDatiView
- (NSMutableArray *)dataArray{
    if (!_dataArray) {
        _dataArray = [NSMutableArray array];
    }
    return _dataArray;
}
- (NSMutableArray *)myResultArray{
    if (!_myResultArray) {
        _myResultArray = [NSMutableArray array];
    }
    return _myResultArray;
}
- (NSMutableArray *)otherResultArray{
    if (!_otherResultArray) {
        _otherResultArray = [NSMutableArray array];
    }
    return _otherResultArray;
}
-(instancetype)initWithFrame:(CGRect)frame {
    self = [super initWithFrame:frame];
    if (self) {
        [self createUI];
    }
    return self;
}
- (void)createUI {
    [self addSubview:self.pkView];
    [self addSubview:self.proBgView];
    [self.proBgView addSubview:self.proView];
    [self addSubview:self.ringLabel];
    [self addSubview:self.wordLabel];
    [self addSubview:self.mTableView];

}
- (UIView *)pkView {
    if(!_pkView){
        _pkView = [[UIView alloc]initWithFrame:CGRectMake(28, 18, SCREEN_W - 56, 111 )];
        
        _pkView.backgroundColor = [UIColor whiteColor];
        [_pkView js_setRoundedCorners:UIRectCornerAllCorners radii:15];
        [_pkView addSubview:self.pkLabel];

        [_pkView addSubview:self.leftUserImg];
        [_pkView addSubview:self.leftUserName];
        [_pkView addSubview:self.rightUserImg];
        [_pkView addSubview:self.rightUserName];
    }
    return _pkView;
}
- (UILabel *)pkLabel {
    if(!_pkLabel){
        _pkLabel = [[UILabel alloc]initWithFrame:CGRectMake(0, 21, 100, 33)];
        _pkLabel.centerX = self.pkView.width/2;
        _pkLabel.text = @"0-0";
        _pkLabel.textColor = COLOR_TOPIC_SELECT;
        _pkLabel.font = PingFangMediumFont(24);
        _pkLabel.textAlignment = NSTextAlignmentCenter;
    }
    return _pkLabel;
}
- (UIImageView *)leftUserImg {
    if(!_leftUserImg){
        _leftUserImg = [[UIImageView alloc]initWithFrame:CGRectMake(47, 15, 44, 44)];
        _leftUserImg.contentMode = UIViewContentModeScaleAspectFill;
//        _leftUserImg.image = [UIImage imageNamed:@"1"];
        [_leftUserImg js_setRoundedCorners:UIRectCornerAllCorners radii:22];
    }
    return _leftUserImg;
}
- (UILabel *)leftUserName {
    if(!_leftUserName){
        _leftUserName = [[UILabel alloc]initWithFrame:CGRectMake(0, 10 + self.leftUserImg.bottom, 100, 22)];
        _leftUserName.centerX = self.leftUserImg.centerX;

//        _leftUserName.text = @"张小明";
        _leftUserName.textColor = [UIColor blackColor];
        _leftUserName.font = PingFangMediumFont(16);
        _leftUserName.textAlignment = NSTextAlignmentCenter;
    }
    return _leftUserName;
}
- (UIImageView *)rightUserImg {
    if(!_rightUserImg){
        _rightUserImg = [[UIImageView alloc]initWithFrame:CGRectMake(self.pkView.width - 91, 15, 44, 44)];
        _rightUserImg.contentMode = UIViewContentModeScaleAspectFill;
//        _rightUserImg.image = [UIImage imageNamed:@"1"];
        [_rightUserImg js_setRoundedCorners:UIRectCornerAllCorners radii:22];
    }
    return _rightUserImg;
}
- (UILabel *)rightUserName {
    if(!_rightUserName){
        _rightUserName = [[UILabel alloc]initWithFrame:CGRectMake(0, 10+ self.rightUserImg.bottom, 100, 22)];
        _rightUserName.centerX = self.rightUserImg.centerX;
//        _rightUserName.text = @"张小明";
        _rightUserName.textColor = [UIColor blackColor];
        _rightUserName.font = PingFangMediumFont(16);
        _rightUserName.textAlignment = NSTextAlignmentCenter;
    }
    return _rightUserName;
}



- (UIView *)proBgView {
    if(!_proBgView){
        _proBgView = [[UIView alloc]initWithFrame:CGRectMake(self.pkView.left, 30 + self.pkView.bottom, self.pkView.width,6)];
        
        _proBgView.backgroundColor = rgbHex(0xffffff, 0.3);
        [_proBgView js_setRoundedCorners:UIRectCornerAllCorners radii:3];
    }
    return _proBgView;
}
- (UIView *)proView {
    if(!_proView){
        _proView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 0, 6)];
        
        _proView.backgroundColor = UIColor.whiteColor;
        [_proView setAllCorner:3];
    }
    return _proView;
}

- (UILabel *)ringLabel {
    if(!_ringLabel){
        _ringLabel = [[UILabel alloc]initWithFrame:CGRectMake(self.pkView.right - 57, 10 +self.proBgView.bottom, 57, 20)];
        _ringLabel.text = @"Ring out";
        _ringLabel.textColor = [UIColor whiteColor];
        _ringLabel.font = PingFangMediumFont(14);
        _ringLabel.textAlignment = NSTextAlignmentRight;
    }
    return _ringLabel;
}

- (UILabel *)wordLabel {
    if(!_wordLabel){
        _wordLabel = [[UILabel alloc]initWithFrame:CGRectMake(0, self.ringLabel.bottom + 20, self.width, 33)];
        _wordLabel.text = @"";
        _wordLabel.textColor = [UIColor whiteColor];
        _wordLabel.font = PingFangMediumFont(24);
        _wordLabel.textAlignment = NSTextAlignmentCenter;
    }
    return _wordLabel;
}
- (UITableView *)mTableView {
    if(!_mTableView){
        _mTableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 60 + self.ringLabel.bottom, SCREEN_W, self.height - self.ringLabel.bottom) style:UITableViewStylePlain];
        _mTableView.backgroundColor = UIColor.clearColor;
        _mTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        _mTableView.delegate = self;
        _mTableView.dataSource = self;
        [_mTableView registerClass:pkDatiCell.class forCellReuseIdentifier:@"pkDatiCell"];
    }
    return _mTableView;
}

#pragma mark ==================== tabledelegate                ======================
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}
- (NSInteger)tableView:(nonnull UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.dataArray.count;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    PkWordModel *wordModel = self.dataArray[indexPath.row];
    return wordModel.height;
}

- (nonnull UITableViewCell *)tableView:(nonnull UITableView *)tableView cellForRowAtIndexPath:(nonnull NSIndexPath *)indexPath {
    pkDatiCell *cell = [tableView dequeueReusableCellWithIdentifier:@"pkDatiCell"];
    [cell updateItemCellModel:self.dataArray[indexPath.row]];
    return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    if (self.muteSelect) {
        return;
    }
    self.muteSelect = YES;
    [self doSelectingWithIndex:indexPath.row];
    dispatch_async(dispatch_get_main_queue(), ^{
        [self.mTableView reloadData];
    });
    [self cancelTimer];
}


#pragma mark   刷新UI
- (void)updateUIWithModel:(id)model {
    if ([model isKindOfClass:PkMatchModel.class]) {
        PkMatchModel *matchModel = (PkMatchModel *)model;
        self.matchModel = matchModel;
        [self.leftUserImg sd_setImageWithURL:[NSURL URLWithString:lApp.useModel.avatar]placeholderImage:[UIImage imageNamed:@"pk_userHeader"]];
        self.leftUserName.text = lApp.useModel.nickname;
        [self.rightUserImg sd_setImageWithURL:[NSURL URLWithString:matchModel.otherUser.avatar]placeholderImage:[UIImage imageNamed:@"pk_userHeader"]];
        self.rightUserName.text = matchModel.otherUser.nickname;
        
        self.proView.width = self.pkView.width;
        [self.dataArray removeAllObjects];
        PkWordModel *wordModel = matchModel.wordsList.firstObject;
        self.rightWord = wordModel;
        self.index = 0;
        self.wordLabel.text = wordModel.words;
        [self.dataArray addObjectsFromArray:wordModel.falseList];
        [self.dataArray insertObject:wordModel atIndex:arc4random()%wordModel.falseList.count];
        dispatch_async(dispatch_get_main_queue(), ^{
            [self.mTableView reloadData];
        });
        
    }
}

- (void)startDati {
    [self.myResultArray removeAllObjects];
    [self.otherResultArray removeAllObjects];
    self.muteSelect = NO;
    [self timeDown];
}

- (void)nextWord {
    self.muteSelect = NO;
    [self.dataArray removeAllObjects];
    self.index ++;
    if (self.matchModel.wordsList.count > self.index) {
        PkWordModel *wordModel = self.matchModel.wordsList[self.index];
        self.rightWord = wordModel;
        self.wordLabel.text = wordModel.words;
        [self.dataArray addObjectsFromArray:wordModel.falseList];
        [self.dataArray insertObject:wordModel atIndex:arc4random()%wordModel.falseList.count];
        dispatch_async(dispatch_get_main_queue(), ^{
            [self.mTableView reloadData];
        });
        [self timeDown];
    }else{
        //公布成绩
        NSLog(@"mytime = %i,result = %@\n othertime = %i,result = %@",self.myPkTime,self.myResultArray,self.otherPkTime,self.otherResultArray);
        if (self.resultBlock) {
            self.resultBlock(self.myPkTime, self.otherPkTime, self.myResultArray, self.otherResultArray);
        }
    }
   
}



- (void)cancelTimer {
//    NSLog(@"time = %i",self.timeNum);
    self.myPkTime += self.timeNum;
    self.otherPkTime += random()%90 + 10;
    self.timeNum = 0;
    if (self.timer) {
        dispatch_source_cancel(self.timer);
        self.timer = nil;
    }
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(3 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        int mySum = [[self.myResultArray valueForKeyPath:@"@sum.intValue"] intValue];
        int otherSum = [[self.otherResultArray valueForKeyPath:@"@sum.intValue"] intValue];
        
        self.pkLabel.text = [NSString stringWithFormat:@"%d-%d",mySum,otherSum];

        [self nextWord];
    });
}

- (void)timeDown {
    __block NSInteger time  = 100; //倒计时时间
    self.timeNum = 0;
    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    self.timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, queue);
    
    dispatch_source_set_timer(self.timer,dispatch_walltime(NULL, 0),0.1*NSEC_PER_SEC, 0); //每秒执行
    @weakify(self);
    dispatch_source_set_event_handler(self.timer, ^{
        @strongify(self);
        self.timeNum ++;
        if(time <= 0){ //倒计时结束，关闭
            [self timeOut];
            [self cancelTimer];
        }else{
            time--;
        }
        dispatch_async(dispatch_get_main_queue(), ^{
            self.proView.width = time*1.00/100*self.pkView.width;
        });
        
    });
    dispatch_resume(self.timer);
}

- (void)timeOut {
    
    [self doSelectingWithIndex:arc4random()%self.dataArray.count];
   
    NSInteger rand = arc4random()%2;
    [self.otherResultArray addObject:[NSString stringWithFormat:@"%li",(long)rand]];
    dispatch_async(dispatch_get_main_queue(), ^{
        [self.mTableView reloadData];
    });
}
- (void)doSelectingWithIndex:(NSInteger)index
{
    NSInteger rand = arc4random()%self.dataArray.count;
    
    for (PkWordModel *model in self.dataArray) {
        model.selected = YES;
        model.isRight = NO;
        model.otherSelected = NO;
        model.mySelected = NO;
        NSInteger row = [self.dataArray indexOfObject:model];
       
        if (row == index) {
            model.mySelected = YES;
            if ([model.ID isEqualToString:self.rightWord.ID]) {
                [self.myResultArray addObject:@"1"];
            }else{
                [self.myResultArray addObject:@"0"];
            }
        }
        if (rand == row) {
            model.otherSelected = YES;
            if ([model.ID isEqualToString:self.rightWord.ID]) {
                [self.otherResultArray addObject:@"1"];
            }else{
                [self.otherResultArray addObject:@"0"];
            }
        }
        if ([model.ID isEqualToString:self.rightWord.ID]) {
            model.isRight = YES;
        }
    }
}
@end
